﻿using Unity.Burst;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
using Unity.Mathematics;
using UnityEngine;

namespace Mars.GpuInstance
{
    [BurstCompile(FloatPrecision = FloatPrecision.Low, FloatMode = FloatMode.Fast)]
    public struct CopyDataJob : IJob
    {
        [NativeDisableContainerSafetyRestriction] [ReadOnly]
        public NativeList<float4x4> input;

        [NativeDisableContainerSafetyRestriction] [ReadOnly]
        public NativeArray<bool> viewIndex;

        [NativeDisableContainerSafetyRestriction] [ReadOnly]
        public NativeArray<int> lodInfo; //lod层级

        [NativeDisableContainerSafetyRestriction] [ReadOnly]
        public NativeList<float4> inputCampData;

        [ReadOnly] public int lod;
        [ReadOnly] public bool isShadow;
        [ReadOnly] public bool hasOffsetMatrix;
        [ReadOnly] public float4x4 offsetMatrix;

        [NativeDisableContainerSafetyRestriction]
        public NativeArray<int> outputCount;

        [NativeDisableContainerSafetyRestriction]
        public NativeArray<float4x4> output;

        [NativeDisableContainerSafetyRestriction]
        public NativeArray<float4> campData;

        public void Execute()
        {
            int len = input.Length;
            for (int i = 0; i < len; i++)
            {
                if (viewIndex[i] && (lod == lodInfo[i] || isShadow))
                {
                    var idx = outputCount[0];
                    if (hasOffsetMatrix)
                    {
                        output[idx] = math.mul(input[i], offsetMatrix);
                    }
                    else
                    {
                        output[idx] = input[i];
                    }

                    campData[idx] = inputCampData[i];
                    outputCount[0]++;
                }
            }
        }
    }
}